package com.example.bluetoothsend

import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothSocket
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf

import androidx.core.view.WindowCompat
import java.io.IOException
import java.util.UUID


import androidx.compose.ui.Alignment
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.AddCircle
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.unit.dp

class MainActivity : ComponentActivity() {
    private lateinit var bluetoothAdapter: BluetoothAdapter
    private val REQUEST_ENABLE_BT = 1
    private val REQUEST_LOCATION_PERMISSION = 2
    private var bluetoothSocket: BluetoothSocket? = null

    private val MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")

    private val discoveredDevices = mutableStateListOf<BluetoothDevice>()
    private val connectionStatus = mutableStateOf("未连接")
    private val messageInput = mutableStateOf("")
    private val receivedMessages = mutableStateListOf<String>()

    private val receiver = object : BroadcastReceiver() {
        @SuppressLint("MissingPermission")
        override fun onReceive(context: Context, intent: Intent) {
            when (intent.action) {
                BluetoothDevice.ACTION_FOUND -> {
                    val device: BluetoothDevice? =
                        intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                    device?.let {
                        if (!discoveredDevices.contains(it)) {
                            discoveredDevices.add(it)
                        }
                    }
                }
                BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> {
                    Toast.makeText(context, "设备搜索完成", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        WindowCompat.setDecorFitsSystemWindows(window, false)

        val bluetoothManager = getSystemService(BluetoothManager::class.java)
        bluetoothAdapter = bluetoothManager?.adapter ?: run {
            Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_LONG).show()
            finish()
            return
        }

        setContent {
            MaterialTheme {
                BluetoothAppUI(
                    devices = discoveredDevices,
                    connectionStatus = connectionStatus.value,
                    messageInput = messageInput.value,
                    receivedMessages = receivedMessages,
                    onScanClicked = { startBluetoothDiscovery() },
                    onDeviceSelected = { device -> connectToDevice(device) },
                    onMessageInputChange = { messageInput.value = it },
                    onSendMessage = { sendMessage(it) }
                )
            }
        }
        checkBluetooth()
    }

    private fun sendMessage(message: String) {
        if (message.isBlank()) {
            Toast.makeText(this, "消息不能为空", Toast.LENGTH_SHORT).show()
            return
        }

        val socket = bluetoothSocket ?: run {
            Toast.makeText(this, "未建立连接", Toast.LENGTH_SHORT).show()
            return
        }

        Thread {
            try {
                val outputStream = socket.outputStream
                val formattedMessage = "$message\n"
                outputStream.write(formattedMessage.toByteArray())

                runOnUiThread {
                    receivedMessages.add("发送: $message")
                    messageInput.value = ""
                }
            } catch (e: IOException) {
                runOnUiThread {
                    receivedMessages.add("发送失败: ${e.message}")
                    connectionStatus.value = "连接断开"
                }
                socket.close()
                bluetoothSocket = null
            }
        }.start()
    }

    @SuppressLint("MissingPermission")
    private fun checkBluetooth() {
        if (!bluetoothAdapter.isEnabled) {
            val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
        } else {
            checkPermissions()
        }
    }

    private fun checkPermissions() {
        val requiredPermissions = mutableListOf<String>()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            requiredPermissions.add(Manifest.permission.BLUETOOTH_CONNECT)
            requiredPermissions.add(Manifest.permission.BLUETOOTH_SCAN)
        } else {
            requiredPermissions.add(Manifest.permission.ACCESS_FINE_LOCATION)
        }

        val missingPermissions = requiredPermissions.filter {
            ActivityCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
        }

        if (missingPermissions.isNotEmpty()) {
            ActivityCompat.requestPermissions(
                this,
                missingPermissions.toTypedArray(),
                REQUEST_LOCATION_PERMISSION
            )
        } else {
            startBluetoothDiscovery()
        }
    }

    @SuppressLint("MissingPermission")
    private fun startBluetoothDiscovery() {
        try {
            unregisterReceiver(receiver)
        } catch (e: Exception) {}
        val filter = IntentFilter().apply {
            addAction(BluetoothDevice.ACTION_FOUND)
            addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
        }
        registerReceiver(receiver, filter)
        discoveredDevices.clear()
        if (bluetoothAdapter.startDiscovery()) {
            Toast.makeText(this, "开始搜索蓝牙设备...", Toast.LENGTH_SHORT).show()
        }
    }

    @SuppressLint("MissingPermission")
    private fun connectToDevice(device: BluetoothDevice) {
        connectionStatus.value = "连接中..."
        bluetoothAdapter.cancelDiscovery()

        Thread {
            var socket: BluetoothSocket? = null
            try {
                socket = device.createRfcommSocketToServiceRecord(MY_UUID).also {
                    it.connect()
                    bluetoothSocket = it
                }

                runOnUiThread {
                    connectionStatus.value = "已连接: ${device.name ?: "未知设备"}"
                    receivedMessages.add("已连接到 ${device.name ?: device.address}")
                }

                while (true) {
                    val inputStream = socket.inputStream
                    val buffer = ByteArray(1024)
                    val bytes = inputStream.read(buffer)
                    val receivedMessage = String(buffer, 0, bytes).trim()

                    runOnUiThread {
                        receivedMessages.add("接收: $receivedMessage")
                    }
                }
            } catch (e: Exception) {
                runOnUiThread {
                    connectionStatus.value = "连接断开"
                    receivedMessages.add("连接错误: ${e.localizedMessage}")
                }
            } finally {
                socket?.close()
                bluetoothSocket = null
            }
        }.start()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            REQUEST_ENABLE_BT -> {
                if (resultCode == RESULT_OK) checkPermissions()
                else Toast.makeText(this, "蓝牙未启用", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            REQUEST_LOCATION_PERMISSION -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    startBluetoothDiscovery()
                }
            }
        }
    }

    @SuppressLint("MissingPermission")
    override fun onDestroy() {
        super.onDestroy()
        try {
            bluetoothSocket?.close()
            unregisterReceiver(receiver)
            bluetoothAdapter.cancelDiscovery()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

@SuppressLint("MissingPermission")
@Composable
fun BluetoothAppUI(
    devices: List<BluetoothDevice>,
    connectionStatus: String,
    messageInput: String,
    receivedMessages: List<String>,
    onScanClicked: () -> Unit,
    onDeviceSelected: (BluetoothDevice) -> Unit,
    onMessageInputChange: (String) -> Unit,
    onSendMessage: (String) -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .systemBarsPadding() // 添加系统栏内边距
            .padding(16.dp),
        verticalArrangement = Arrangement.SpaceBetween
    ) {
        Column(modifier = Modifier.weight(1f)) {
            ConnectionStatus(connectionStatus)
            ScanButton(onScanClicked)
            DeviceList(devices, onDeviceSelected)
            MessageHistory(receivedMessages)
        }
        MessageInput(
            message = messageInput,
            onMessageChange = onMessageInputChange,
            onSend = onSendMessage,
            enabled = connectionStatus.contains("已连接")
        )
    }
}

@Composable
private fun ConnectionStatus(status: String) {
    Text(
        text = "蓝牙状态: $status",
        color = when {
            status.contains("已连接") -> Color.Green
            status.contains("连接中") -> Color.Blue
            else -> Color.Red
        },
        modifier = Modifier.padding(8.dp)
    )
}

@Composable
private fun ScanButton(onClick: () -> Unit) {
    Button(
        onClick = onClick,
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 8.dp)
    ) {
        Text("扫描蓝牙设备")
    }
}

@SuppressLint("MissingPermission")
@Composable
private fun DeviceList(
    devices: List<BluetoothDevice>,
    onDeviceSelected: (BluetoothDevice) -> Unit
) {

    Text("已发现设备 (点击连接):", modifier = Modifier.padding(top = 8.dp))
    LazyColumn(
        modifier = Modifier
            .fillMaxWidth()
            .heightIn(max = 200.dp)
            .padding(8.dp)
    ) {
        items(devices) { device ->
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(4.dp),
                onClick = { onDeviceSelected(device) }
            ) {
                Column(modifier = Modifier.padding(8.dp)) {
                    Text(
                        text = device.name ?: "未知设备",
                        style = MaterialTheme.typography.bodyLarge
                    )
                    Text(
                        text = device.address,
                        style = MaterialTheme.typography.bodySmall,
                        color = Color.Gray
                    )
                }
            }
        }
    }
}

@Composable
private fun MessageHistory(messages: List<String>) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .fillMaxWidth()
            .padding(vertical = 8.dp),
        elevation = CardDefaults.cardElevation(4.dp)
    ) {
        LazyColumn(modifier = Modifier.padding(8.dp)) {
            items(messages) { message ->
                Text(
                    text = message,
                    modifier = Modifier.padding(4.dp),
                    color = when {
                        message.startsWith("发送") -> Color.Blue
                        message.startsWith("接收") -> Color.Green
                        else -> Color.Gray
                    }
                )
                Divider()
            }
        }
    }
}

@Composable
private fun MessageInput(
    message: String,
    onMessageChange: (String) -> Unit,
    onSend: (String) -> Unit,
    enabled: Boolean
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(top = 8.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        TextField(
            value = message,
            onValueChange = onMessageChange,
            modifier = Modifier.weight(1f),
            placeholder = { Text("输入消息...") },
            enabled = enabled
        )
        Button(
            onClick = { onSend(message) },
            modifier = Modifier.padding(start = 8.dp),
            enabled = enabled && message.isNotBlank()
        ) {
            Text("发送")
        }
    }
}


